import * as vscode from "vscode";
import { exec } from "child_process";
import { showErrorMessage } from "./message";
import * as os from "os";
import { OutputChannel } from "./output";

/**
 * 检查Node.js环境是否可用
 * @param context VS Code扩展上下文
 * @returns 返回一个Promise，解析为布尔值表示Node.js环境是否可用
 */
export async function checkNodeEnvironment(
  context: vscode.ExtensionContext,
): Promise<boolean> {
  try {
    const hasNodeJs = await checkNodeCommand(context);
    if (!hasNodeJs) {
      const platform = os.platform();
      let installCommand = "";

      if (platform === "win32") {
        installCommand =
          "winget install --id OpenJS.NodeJS.LTS --silent --accept-package-agreements --accept-source-agreements";
      } else if (platform === "darwin") {
        installCommand = "brew install node";
      } else if (platform === "linux") {
        installCommand =
          "curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - && sudo apt-get install -y nodejs";
      }

      const result = await vscode.window.showErrorMessage(
        "ArenaPro：未检测到Node.js环境，请先安装Node.js才能使用完整功能。",
        "一键安装",
        "取消",
      );

      if (result === "一键安装" && installCommand) {
        // 使用已有的OutputChannel显示命令输出
        OutputChannel.setOutputChannel("Node.js 安装");
        const outputChannel = OutputChannel.getInstance();
        outputChannel.clear();
        outputChannel.show();
        outputChannel.appendLine(`执行命令: ${installCommand}`);

        const childProcess = exec(installCommand);

        // 捕获标准输出
        childProcess.stdout?.on("data", (data) => {
          outputChannel.appendLine(data.toString());
        });

        // 捕获标准错误
        childProcess.stderr?.on("data", (data) => {
          outputChannel.appendLine(data.toString());
        });

        // 监听进程完成
        childProcess.on("close", (code) => {
          if (code !== 0) {
            outputChannel.error(`\n安装失败，退出码: ${code}`);
            vscode.window.showErrorMessage(`安装Node.js失败，请尝试手动安装。`);

            // 如果安装失败，打开安装教程
            const nodeJsDoc = vscode.Uri.joinPath(
              context.extensionUri,
              "md",
              "nodejs.md",
            );
            vscode.commands.executeCommand("markdown.showPreview", nodeJsDoc);
          } else {
            outputChannel.appendLine("\n安装成功！");

            vscode.window
              .showInformationMessage(
                "Node.js安装成功，请重启VS Code以使用完整功能。",
                "立即重启",
              )
              .then((selection) => {
                if (selection === "立即重启") {
                  // 重启VSCode
                  vscode.commands.executeCommand(
                    "workbench.action.reloadWindow",
                  );
                }
              });
          }
        });
      }
      return false;
    }
    return true;
  } catch (error) {
    showErrorMessage(`检查Node.js环境时发生错误: ${error}`);
    return false;
  }
}

/**
 * 检查Git环境是否可用
 * @param context VS Code扩展上下文
 * @returns 返回一个Promise，解析为布尔值表示Git环境是否可用
 */
export async function checkGitEnvironment(
  context: vscode.ExtensionContext,
): Promise<boolean> {
  try {
    const hasGit = await checkGitCommand();
    if (!hasGit) {
      const platform = os.platform();
      let installCommand = "";

      if (platform === "win32") {
        installCommand =
          "winget install --id Git.Git --silent --accept-package-agreements --accept-source-agreements";
      } else if (platform === "darwin") {
        installCommand = "brew install git";
      } else if (platform === "linux") {
        installCommand = "sudo apt-get update && sudo apt-get install -y git";
      }

      const result = await vscode.window.showInformationMessage(
        "ArenaPro：未检测到Git环境，请先安装Git才能使用完整功能。",
        "一键安装",
        "取消",
      );

      if (result === "一键安装" && installCommand) {
        // 使用已有的OutputChannel显示命令输出
        OutputChannel.setOutputChannel("Git 安装");
        const outputChannel = OutputChannel.getInstance();
        outputChannel.clear();
        outputChannel.show();
        outputChannel.appendLine(`执行命令: ${installCommand}`);

        const childProcess = exec(installCommand);

        // 捕获标准输出
        childProcess.stdout?.on("data", (data) => {
          outputChannel.appendLine(data.toString());
        });

        // 捕获标准错误
        childProcess.stderr?.on("data", (data) => {
          outputChannel.appendLine(data.toString());
        });

        // 监听进程完成
        childProcess.on("close", (code) => {
          if (code !== 0) {
            outputChannel.error(`\n安装失败，退出码: ${code}`);
            vscode.window.showErrorMessage(
              `安装Git失败，请尝试手动安装。地址：https://git-scm.com/downloads`,
            );
          } else {
            outputChannel.appendLine("\n安装成功完成！");
            vscode.window
              .showInformationMessage(
                "Git安装成功，请重启VS Code以使用完整功能。",
                "立即重启",
              )
              .then((selection) => {
                if (selection === "立即重启") {
                  // 重启VSCode
                  vscode.commands.executeCommand(
                    "workbench.action.reloadWindow",
                  );
                }
              });
          }
        });
      }
      return false;
    }
    return true;
  } catch (error) {
    showErrorMessage(`检查Git环境时发生错误: ${error}`);
    return false;
  }
}

/**
 * 检查Node.js命令是否可用
 * @returns 返回一个Promise，解析为布尔值表示Node.js命令是否可用
 */
async function checkNodeCommand(
  context: vscode.ExtensionContext,
): Promise<boolean> {
  return new Promise((resolve) => {
    const cmd = "node -v";

    exec(cmd, (error, stdout) => {
      if (error) {
        console.error("Node.js command check failed:", error);
        resolve(false);
        return;
      }

      // 解析版本号
      const version = stdout.trim().replace("v", "");
      const majorVersion = parseInt(version.split(".")[0]);

      if (majorVersion < 20) {
        vscode.window
          .showWarningMessage(
            `当前Node.js版本(${version})过低，建议升级到v20或更高版本以获得更好的体验。`,
            "了解更多",
          )
          .then((selection) => {
            if (selection === "了解更多") {
              const nodeJsDoc = vscode.Uri.joinPath(
                context.extensionUri,
                "md",
                "nodejs.md",
              );
              vscode.commands.executeCommand("markdown.showPreview", nodeJsDoc);
            }
          });
      }

      resolve(true);
    });
  });
}

/**
 * 检查Git命令是否可用
 * @returns 返回一个Promise，解析为布尔值表示Git命令是否可用
 */
async function checkGitCommand(): Promise<boolean> {
  return new Promise((resolve) => {
    const cmd = "git --version";

    exec(cmd, (error, stdout) => {
      if (error) {
        console.error("Git command check failed:", error);
        resolve(false);
        return;
      }

      resolve(true);
    });
  });
}
